import asyncio

from django.http import HttpResponse

from communication.asyncClient import AsyncClient
from public.message import chat_msg
from webpage import get_web_client
from webpage.mei.urls import register_post


async def get_ai_chat(text):
    async with AsyncClient('ai_chat') as client:
        ret = await client.send(text)
        return ret


@register_post('chat')
def chat(request):
    user_id = int(request.user.username or 0)
    text = request.body.decode('utf-8')
    ret = get_web_client().send(chat_msg.build(
        user_id=user_id,
        group_id=0,
        text=text,
    ))
    if not ret:  # TODO ai回复设置为仅登录可用，并且对每个账号限制频率和次数
        ret = asyncio.run(get_ai_chat(text))
    return HttpResponse(ret)
